package mqtt_client

import (
	"fmt"
	mqtt "paho"
	"time"
)

var recvMsg mqtt.MessageHandler = func(client mqtt.Client, message mqtt.Message) {
	// 获取消息
	fmt.Println("receive a message", message.Topic(), string(message.Payload()))
}

type Client struct {
	client mqtt.Client
	topics []string
}

func InitOption(ip string, port int, username string, password string, client_id string) *mqtt.ClientOptions {
	server := fmt.Sprintf("tcp://%s:%d", ip, port)
	option := mqtt.NewClientOptions().AddBroker(server).SetUsername(username).SetPassword(password)
	option.SetDefaultPublishHandler(recvMsg)
	option.SetClientID(client_id)
	return option
}

func (c *Client) InitClient(option *mqtt.ClientOptions) mqtt.Client {
	//server := fmt.Sprintf("tcp://%s:%d", ip, port)
	//fmt.Println(server)
	//option := mqtt.NewClientOptions().AddBroker(server).SetUsername("yuzhen").SetPassword("password")
	//option.SetDefaultPublishHandler(recvMsg)
	//option.SetClientID("oh_its_me")

	client := mqtt.NewClient(option)
	c.client = client
	c.topics = []string{}

	return client
}

func (c *Client) Connect() {
	token := c.client.Connect()
	if token.WaitTimeout(time.Duration(60)*time.Second) && token.Wait() && token.Error() != nil {
		fmt.Println("error got", token.Error())
		return
	}
	c.AddSubscript("go/MqTT/sub")
	c.Subscript()
}

func (c *Client) Publish(topic string, message string) int {
	token_p := c.client.Publish(topic, 1, false, message)
	token_p.Wait()
	time.Sleep(time.Duration(5) * time.Second)
	if token_p.Error() == nil {
		return 0
	} else {
		return 1
	}
}

func (c *Client) Subscript() {
	for _, t := range c.topics {
		c.client.Subscribe(t, 1, recvMsg)
	}
}

func (c *Client) AddSubscript(topic string) {
	c.topics = append(c.topics, topic)
}
